package com.dushibao.admin.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dushibao.admin.handler.SpringContextHolder;
import com.dushibao.admin.model.Admin;
import com.dushibao.admin.service.IAdminService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    /**
     * 1、校验session中的登录账号
     * 2、校验cookie中的账号
     * 只有session和cookie中的账号都为空,那么跳转到登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、拿到session中的admin
        Object admin = request.getSession().getAttribute("admin");

        Admin cookieAdmin = getAdminFromCookie(request);

        if(admin == null && cookieAdmin == null){

            response.sendRedirect("/admin/login");

            return false;
        }

        if(admin == null){
            request.getSession().setAttribute("admin",cookieAdmin);
        }

        return true;

    }

    public Admin getAdminFromCookie(HttpServletRequest request){

        Cookie[] cookies = request.getCookies();

        String userName = null;
        String password = null;

        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {

                if("adminUserName".equalsIgnoreCase(cookie.getName())){
                     userName = cookie.getValue();
                }

                if("adminPassword".equalsIgnoreCase(cookie.getName())){
                     password = cookie.getValue();
                }

            }
        }

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userName);
        queryWrapper.eq("password",password);

        Admin admin = SpringContextHolder.getBean(IAdminService.class).getOne(queryWrapper);

        return admin;
    }

}
